package main

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/astaxie/beego/logs"
	"github.com/joho/godotenv"
	"github.com/linsongze/loadtest"
)

func httpGet(url string) {
	timestamp := time.Now().Unix()
	timestampStr := strconv.FormatInt(timestamp, 10)
	resp, err := http.Get(url + "?timestamp=" + timestampStr)
	if err != nil {
		fmt.Println("request erorr")
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		//fmt.Println("request erorr", err)
		logs.Error("request erorr", err)
	}
	if err != nil {
		//fmt.Println("respone erorr", err)
		logs.Error("request erorr", err)
	} else {
		//fmt.Println("respone :", string(body))
		logs.Error("respone success:", string(body))
	}
}

func readLineRequest(fileName string, handler func(string)) error {
	f, err := os.Open(fileName)
	if err != nil {
		return err
	}
	buf := bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		// go handler(line)

		// for i = 0; i < count; i++ {
		go handler(line)
		// }

		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
	}
	return nil
}
func Print(line string) {
	// fmt.Println(i, line)

	fmt.Printf("%s \n", line)
	// quit <- 0
}

func weiXinPost() {
	//timestamp := time.Now().Unix()
	//timestampStr := strconv.FormatInt(timestamp, 10)
	//timestampStr := strconv.FormatUint(timestamp, 10)
	timeOut := 500 //rand.Intn(50)
	//url := "https://weixinentrance.yihu.com/WxReceiver/receiver/enter?oriid=gh_3e600160bbf9&signature=3514a5aa70175f5fa458d02cd653d576a12c615e&timestamp=" + timestampStr + "&nonce=578632122&openid=oeB2VjojwenJ_dPeKayzSsVKJong&timeOut=" + strconv.Itoa(timeOut)
	//payload := strings.NewReader("<xml><ToUserName><![CDATA[gh_3e600160bbf9]]></ToUserName> <FromUserName><![CDATA[oeB2VjojwenJ_dPeKayzSsVKJong]]></FromUserName> <CreateTime>" + timestampStr + "</CreateTime> <MsgType><![CDATA[event]]></MsgType> <Event><![CDATA[SCAN]]></Event> <EventKey><![CDATA[94705]]></EventKey> <Ticket><![CDATA[gQHw8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyRXZtbTRwVXRhbGUxMDAwME0wM0kAAgSjrXFaAwQAAAAA]]></Ticket> </xml>")

	url := "http://172.18.21.25:8085/redis/defaultdata"
	payload := strings.NewReader("<xml>asdfasdfasdf/xml>")

	//fmt.Println("request url :", url)
	//fmt.Println("request body :", payload)
	http.DefaultClient.Timeout = time.Duration(timeOut) * time.Millisecond

	req, err := http.NewRequest("POST", url, payload)
	if err != nil {
		//fmt.Println("Request error :", err)
		logs.Error("request error :", err)
		return
	}

	req.Header.Add("content-type", "application/xml")
	req.Header.Add("cache-control", "no-cache")
	res, err := http.DefaultClient.Do(req)
	if err != nil {
		//fmt.Println("Request error :", err)
		logs.Error("respone error :", err)
		return
	}

	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		//panic(err)
		//fmt.Println("respone error :", err)
		logs.Error("respone error :", err)
	} else {
		//fmt.Println(res)
		//fmt.Println(string(body))
		logs.Error("respone success :", string(body))
	}

}

func main() {
	// count := 0
	// outCount := 0
	// for {
	// 	if count == 10000 {
	// 		return
	// 	}
	// 	t1 := time.Now() // get current time
	// 	for i := 0; i < 100; i++ {

	// 		//获取时间戳

	// 	}
	// 	count += 100
	// 	elapsed := time.Since(t1)
	// 	fmt.Println("run 100 elapsed : ", elapsed)
	// 	fmt.Println("sleep 1 second :", time.Now(), count, outCount)
	// 	time.Sleep(time.Second * 1)
	// }

	logs.SetLogger("console")
	logs.SetLogger(logs.AdapterFile, `{"filename":"project.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10}`)

	// 配置
	err := godotenv.Load()
	if err != nil {
		logs.Error(err)
	}

	urlfile := "urls.txt"
	// count, _ := file.CountFileLine(urlfile)
	readLineRequest(urlfile, Print)

	threadNumStr := os.Getenv("thread_num")
	threadNum, err := strconv.Atoi(threadNumStr)
	if err != nil {
		threadNum = 200
		logs.Error("strconv.Atoi(threadNumStr):", err)
	}

	//http://weixinauthtest.yihu.com/?m=wxauth&c=wxauth&tourl=http%3A%2F%2Fweixinauthtest.yihu.com%2Findex.php%2FWxauth%2FIndex%2Ftest.html%3F_channel_id%3D9000286&code=021byWo21DM39P1fomp21i8Qo21byWoi&state=1&_use_file_config=1

	//http://weixinauthtest.yihu.com/?m=wxauth&c=wxauth&tourl=http%3A%2F%2Fweixinauthtest.yihu.com%2Findex.php%2FWxauth%2FIndex%2Ftest.html%3F_channel_id%3D9000286&code=021byWo21DM39P1fomp21i8Qo21byWoi&state=1

	url := "http://weixinauthtest.yihu.com/?m=wxauth&c=wxauth&tourl=http%3A%2F%2Fweixinauthtest.yihu.com%2Findex.php%2FWxauth%2FIndex%2Ftest.html%3F_channel_id%3D9000286&code=021byWo21DM39P1fomp21i8Qo21byWoi&state=1"
	runner := loadtest.New()
	runner.SetThreadNum(threadNum)
	runner.SetRunFunction(func() {
		//weiXinPost()
		httpGet(url)
		time.Sleep(time.Millisecond * 5)
	})
	runner.Start()

}
